class Solution(object):
    def monotoneIncreasingDigits(self, n):
        """
        :type n: int
        :rtype: int
        """
        num = list(str(n))

        #从后往前遍历，若前面数字小于后面的，则前面数字减1，后面数据变为9
        flag = len(num)
        for i in range(len(num)-1, 0, -1):
            if num[i-1] > num[i]:
                num[i-1] = chr(ord(num[i-1]) - 1)
                flag = i
        
        for i in range(flag, len(num)):
            num[i] = '9'
        return int("".join(num))
